package com.hundsun.cprs.yyt.service.dilivery.service.impl;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.hundsun.cprs.yyt.common.enums.EnumAreaCode;
import com.hundsun.cprs.yyt.common.enums.EnumBusinessCode;
import com.hundsun.cprs.yyt.common.exception.ServiceCodeException;
import com.hundsun.cprs.yyt.service.common.enums.EnumSmsCode;
import com.hundsun.cprs.yyt.service.common.service.RemoteSmsService;
import com.hundsun.cprs.yyt.service.dilivery.dao.DeliveryDao;
import com.hundsun.cprs.yyt.service.dilivery.domain.Delivery;
import com.hundsun.cprs.yyt.service.goods.domain.GoodsSpecs;
import com.hundsun.cprs.yyt.service.goods.domain.GoodsStockLog;
import com.hundsun.cprs.yyt.service.goods.enums.EnumStockType;
import com.hundsun.cprs.yyt.service.goods.service.GoodsSkuService;
import com.hundsun.cprs.yyt.service.goods.service.GoodsStockLogService;
import com.hundsun.cprs.yyt.service.order.domain.OrderItem;
import com.hundsun.cprs.yyt.service.order.dto.OrderInfo;
import com.hundsun.cprs.yyt.service.order.enums.EnumDeliveryMethod;
import com.hundsun.cprs.yyt.service.order.enums.EnumsOrderStatus;
import com.hundsun.cprs.yyt.service.order.service.OrderService;
import com.hundsun.cprs.yyt.service.trade.domain.TradeEntrust;
import com.hundsun.cprs.yyt.service.trade.enums.EnumTradeEntrustStatus;
import com.hundsun.cprs.yyt.service.trade.enums.EnumTradeStatus;
import com.hundsun.cprs.yyt.service.trade.service.TradeEntrustService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.hundsun.cprs.yyt.common.base.BaseService;
import com.hundsun.cprs.yyt.service.dilivery.enums.EnumDeliveryStatus;
import com.hundsun.cprs.yyt.service.dilivery.service.DeliveryService;
import org.springframework.transaction.annotation.Transactional;

@Service
public class DeliveryServiceImpl extends BaseService implements DeliveryService {
    
    @Autowired
    private DeliveryDao deliveryDao;
    @Autowired
    private OrderService orderService;
    @Autowired
    private GoodsSkuService goodsSkuService;
    @Autowired
    private RemoteSmsService remoteSmsService;
    @Autowired
    private TradeEntrustService tradeEntrustService;

    @Override
    @Transactional
    public void createDelivery(Delivery delivery) {
        //1.如果是零售区的订单，则需要校验委买单是否已成,自提方式除外
        OrderInfo orderInfo = orderService.selectOrderInfoById(delivery.getOrderId());
        if (orderInfo.getStatus() != EnumsOrderStatus.WAIT_DELIVERY.getStatus()){
            throw new ServiceCodeException(EnumBusinessCode.BUSINESS_1523.getErrorNo(),EnumBusinessCode.BUSINESS_1523.getErrorInfo());
        }
        OrderItem orderItem = orderInfo.getOrderItems().get(0);
        if(orderInfo.getAreaCode().equals(EnumAreaCode.RETAIL_AREA.getCode())){
            //根据订单编号查询委托单详情
            TradeEntrust tradeEntrust = tradeEntrustService.getTradeEntrustByOrderSn(orderInfo.getSn());
            if (tradeEntrust == null){
                throw new ServiceCodeException(EnumBusinessCode.BUSINESS_1520.getErrorNo(),EnumBusinessCode.BUSINESS_1520.getErrorInfo());
            }
            if (!tradeEntrust.getStatus().equals(EnumTradeStatus.DEALT.getStatus())){
                throw new ServiceCodeException(EnumBusinessCode.BUSINESS_1521.getErrorNo(),EnumBusinessCode.BUSINESS_1521.getErrorInfo());
            }
            //零售区发货数量直接就是订单的商品总数
            delivery.setQuantity(orderInfo.getQuantity().longValue());
        }else{
            //批发区委售单发货数量，需要用订单商品总数减去已成数量
            Long quantity = orderItem.getQuantity() - orderItem.getShippedQuantity();
            delivery.setQuantity(quantity);
        }
        //2.生成物流单
        delivery.setDeliveryTime(new Date());
        deliveryDao.insert(delivery);
        //3.修改订单状态为待收货
        orderInfo.setStatus(EnumsOrderStatus.DELIVERED.getStatus());
        orderService.updateOrderStatus(orderInfo);
        //4.库存变更
        int outAmount = orderItem.getQuantity().intValue();
        goodsSkuService.deductGoodsStock(orderItem.getSkuId(),outAmount,outAmount);
        //5.发货成功，给收货人发短信通知
        sendSmsToReciver(orderInfo,delivery);
    }

    @Override
    public Delivery selectDeliveryInfo(Long orderId) {
        return deliveryDao.selectByPrimaryKey(orderId);
    }

    /**
     * 给收货人发送短信提醒
     * @param orderInfo
     *
     * */
    protected void sendSmsToReciver(OrderInfo orderInfo,Delivery delivery){
        Map<String, String> params = new HashMap<>();
        params.put("orderNo",orderInfo.getSn());
        params.put("goodsName",orderInfo.getOrderItems().get(0).getGoodsName());
        String smsCode="";
        if (orderInfo.getDeliveryType()==EnumDeliveryMethod.SELFGET.ordinal()){
            //自提短信
            smsCode = EnumSmsCode.SELFGET_SMS_CODE.getCode();
        }else{
            //普通物流短信
            params.put("logisticsCompany",delivery.getLogisticsCompany());
            params.put("batchNumber",delivery.getBatchNumber());
            smsCode = EnumSmsCode.DELIVERY_SMS_CODE.getCode();
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date = sdf.format(new Date());
        remoteSmsService.toUserSendSms(orderInfo.getPhone(), smsCode, params, orderInfo.getUserId(), date);
    }
}
